package com.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.health.constant.MessageConstant;
import com.health.dao.MemberDao;
import com.health.dao.OrderDao;
import com.health.dao.ReportDao;
import com.health.entity.PageResult;
import com.health.entity.QueryPageBean;
import com.health.entity.Result;
import com.health.pojo.Member;
import com.health.pojo.Order;
import com.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Classname MemberServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/3/17 14:48
 * @Author RainGrd
 */
@Service(interfaceClass = MemberService.class)
@Transactional
@Slf4j
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private ReportDao reportDao;

    @Autowired
    private OrderDao orderDao;


    @Override
    public List<Integer> findMemberCountByMonth(List<String> month) {
        List<Integer> list = new ArrayList<>();
        for (String m : month) {
//            m = m + "-31";//格式：2019.04.31
            log.info("m:{}", m);
            Integer count = memberDao.findMemberCountBeforeDate(m);
            list.add(count);
        }
        return list;
    }

    @Override
    public PageResult queryMemberPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Member> page = memberDao.selectByCondition(queryPageBean.getQueryString());
        log.info("查询出来的会员列表:{}", page.getResult());
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public int saveMember(Member member) {
        //设置注册时间
        member.setRegTime(new Date());
        return memberDao.insertMember(member);
    }

    @Override
    public int editMember(Member member) {
        return memberDao.updateMember(member);
    }

    @Override
    public Result deleteMemberById(Integer id) {
        log.info("删除会员的Id:{}", id);
        try {
            //根据此Id查询预约
            Order order = orderDao.selectOrderByMemberId(id);
            if (order != null) {
                return Result.error(MessageConstant.DELETE_REPORT_FLAG);
            }
            int i = memberDao.deleteMemberById(id);
            return i > 0 ? Result.success(MessageConstant.DELETE_MEMBER_SUCCESS) : Result.error(MessageConstant.DELETE_MEMBER_FAIL);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error(MessageConstant.DELETE_MEMBER_FAIL);//新增失败
        }

    }
}
